package test

import (
	"fmt"
	"im_study_go_chat/models"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"

	_ "gorm.io/gorm"
)

// UserInfo User 定义model结构体
type UserInfo struct {
	gorm.Model
	Name   string `gorm:"type:varchar(255); not null" json:"name" binding:"required"`
	Gender string `gorm:"type:varchar(255); not null" json:"gender" binding:"required"`
}

// List 结构体
type List struct {
	gorm.Model        // 主键
	Name       string `gorm:"type:varchar(20); not null" json:"name" binding:"required"`
	State      string `gorm:"type:varchar(20); not null" json:"state" binding:"required"`
	Phone      string `gorm:"type:varchar(20); not null" json:"phone" binding:"required"`
	Email      string `gorm:"type:varchar(40); not null" json:"email" binding:"required"`
	Address    string `gorm:"type:varchar(200); not null" json:"address" binding:"required"`
}

func TestMysql() {
	fmt.Println("hello")
	dsn := "root:123456@tcp(127.0.0.1:3306)/kk?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})

	fmt.Println("db = ", db)
	fmt.Println("err = ", err)

	// 连接池
	sqlDB, err := db.DB()
	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(10)
	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(100)
	// SetConnMaxLifetime 设置了连接可复用的最大时间。
	sqlDB.SetConnMaxLifetime(10 * time.Second) //

	createUserBasic(db)
	//readData(db)
}

func createUserBasic(db *gorm.DB) {
	err := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8").AutoMigrate(&models.UserBasic{})
	if err != nil {
		return
	}
	rr := db.Create(&models.UserBasic{
		Model:         gorm.Model{},
		Name:          "娜娜",
		Password:      "123456",
		Phone:         "13123456789",
		Email:         "12@qq.com",
		Identidy:      "",
		ClientIp:      "",
		ClientPort:    "",
		LoginTime:     0,
		HeartbeatTime: 0,
		LoginOutTime:  0,
		IsLogout:      false,
		DeviceInfo:    "",
	})
	fmt.Println(rr)
}

// 初始化和插入数据
func initNewData(db *gorm.DB) {
	// 自动初始化table,不存在就会创建,设置格式为utf8,便于MySQL5.7或版本以下自动创建的表插入中文
	err := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8").AutoMigrate(&List{}, &UserInfo{})
	if err != nil {
		return
	}
	// 插入数据
	rr := db.Create(&UserInfo{
		Name: "张三", Gender: "男",
	})
	fmt.Println("插入数据,", rr)

	db.Create(&UserInfo{
		Name: "李四", Gender: "男",
	})
	db.Create(&UserInfo{
		Name: "王舞", Gender: "女",
	})
}

func readData(db *gorm.DB) {
	// 读取数据
	var kUser UserInfo
	kk := db.First(&kUser, 1)
	fmt.Println("查询user表,id=1的结果", kk)
	// 更新数据一个字段
	db.Model(&kUser).Update("name", "吴总")
	// 更新多个字段
	db.Model(&kUser).Updates(UserInfo{
		Name: "孙尚香", Gender: "女",
	})
}

func delData(db *gorm.DB) {
	// 删除数据
	var kUser UserInfo
	db.Model(&kUser).Delete(&kUser, 1)
}
